/**
 * 项目辅助模块配置
 */

// 从简化版配置导入已有的工具
const {
  errorHelper,
  cacheHelper,
  validate,
  timeHelper,
  statusHelper,
  logHelper,
  networkHelper
} = require('./simple_helpers_config.js');

// 状态字段助手
let stateFieldHelper;
try {
  stateFieldHelper = require('../helpers/state_field_helper');
} catch (error) {
  console.warn('无法导入状态字段助手，使用默认实现');
  stateFieldHelper = {};
}

// 基础页面助手
const pageHelper = {
  // 弹窗相关
  showModal: (title, content, callback = null) => {
    wx.showModal({
      title,
      content,
      showCancel: false,
      success: (res) => {
        if (callback) callback(res.confirm);
      }
    });
  },
  
  showConfirm: (title, content, callback = null, cancelCallback = null) => {
    wx.showModal({
      title,
      content,
      showCancel: true,
      success: (res) => {
        if (res.confirm && callback) {
          callback();
        } else if (res.cancel && cancelCallback) {
          cancelCallback();
        }
      }
    });
  },
  
  showSuccToast: (title, duration = 1500) => {
    wx.showToast({
      title,
      icon: 'success',
      duration
    });
  },
  
  showErrToast: (title, duration = 1500) => {
    wx.showToast({
      title,
      icon: 'error',
      duration
    });
  },
  
  showNoneToast: (title, duration = 1500) => {
    wx.showToast({
      title,
      icon: 'none',
      duration
    });
  },
  
  // 页面数据处理
  dataset: (e, key) => e?.currentTarget?.dataset?.[key],
  
  getPrevPage: () => {
    const pages = getCurrentPages();
    if (pages.length < 2) return null;
    return pages[pages.length - 2];
  },
  
  // 页面路由
  goto: (url, type = 'navigateTo') => {
    switch (type) {
      case 'navigateTo':
        wx.navigateTo({ url });
        break;
      case 'redirectTo':
        wx.redirectTo({ url });
        break;
      case 'reLaunch':
        wx.reLaunch({ url });
        break;
      case 'switchTab':
        wx.switchTab({ url });
        break;
      default:
        wx.navigateTo({ url });
    }
  },
  
  gotoWithParams: (url, params, type = 'navigateTo') => {
    if (params) {
      const query = Object.keys(params)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&');
      
      url = url.includes('?') ? `${url}&${query}` : `${url}?${query}`;
    }
    
    pageHelper.goto(url, type);
  }
};

// 云函数助手
const cloudHelper = {
  callCloud: async (name, data, options = {}) => {
    try {
      const loading = options.loading !== false;
      
      if (loading) {
        wx.showLoading({
          title: options.title || '加载中...',
          mask: true
        });
      }
      
      // 检查是否在企业微信环境
      let isQyWx = false;
      try {
        const sysInfo = await new Promise((resolve) => {
          wx.getSystemInfo({
            success: resolve,
            fail: () => resolve({})
          });
        });
        isQyWx = sysInfo.environment === 'wxwork';
        
        if (isQyWx) {
          console.log('[CLOUD] 检测到企业微信环境');
          // 添加环境标记
          if (!data) data = {};
          data.isQyWx = true;
          data.env = 'qywx';
        }
      } catch (e) {
        console.error('[CLOUD] 检测环境失败', e);
      }
      
      // 添加重试机制
      let retryCount = 0;
      const maxRetry = 2;
      const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
      
      // 重试函数
      const callWithRetry = async () => {
        try {
          // 调用云函数
          const res = await wx.cloud.callFunction({
            name,
            data
          });
          
          return res;
        } catch (err) {
          console.error(`[CLOUD] 调用失败 (${retryCount}): ${err.message}`);
          
          if (retryCount < maxRetry) {
            retryCount++;
            await delay(1000); // 等待1秒后重试
            return callWithRetry();
          }
          throw err;
        }
      };
      
      // 执行带重试的调用
      const res = await callWithRetry();
      
      if (loading) wx.hideLoading();
      
      // 处理返回结果
      if (res.result && res.result.code === 200) {
        return res.result;
      } else {
        // 处理错误
        const message = res.result?.msg || '操作失败，请重试';
        
        if (!options.silent) {
          wx.showToast({
            title: message,
            icon: 'none'
          });
        }
        
        // 记录错误
        errorHelper.logError(`云函数调用失败: ${name}`, {
          error: res.result?.msg,
          code: res.result?.code,
          data
        });
        
        throw new Error(message);
      }
    } catch (error) {
      wx.hideLoading();
      
      if (!options.silent) {
        wx.showToast({
          title: error.message || '系统错误，请重试',
          icon: 'none'
        });
      }
      
      // 记录错误
      errorHelper.logError(`云函数异常: ${name}`, error);
      
      throw error;
    }
  },
  
  callCloudData: async (name, data, options = {}) => {
    try {
      const result = await cloudHelper.callCloud(name, data, options);
      return result.data;
    } catch (error) {
      throw error;
    }
  },
  
  callCloudSumbit: async (name, data, options = {}) => {
    try {
      const result = await cloudHelper.callCloud(name, data, options);
      
      if (!options.noSuccToast) {
        pageHelper.showSuccToast('操作成功');
      }
      
      return result;
    } catch (error) {
      throw error;
    }
  }
};

// 日期处理助手
const dateHelper = {
  // 日期格式化
  format: (date, format = 'YYYY-MM-DD') => {
    if (!date) return '';
    
    date = new Date(date);
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return format
      .replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds);
  },
  
  // 获取今天的日期字符串
  today: (format = 'YYYY-MM-DD') => {
    return dateHelper.format(new Date(), format);
  },
  
  // 获取明天的日期字符串
  tomorrow: (format = 'YYYY-MM-DD') => {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    return dateHelper.format(tomorrow, format);
  },
  
  // 获取昨天的日期字符串
  yesterday: (format = 'YYYY-MM-DD') => {
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    return dateHelper.format(yesterday, format);
  }
};

// 简单数据处理助手
const dataHelper = {
  formatData: (data) => data,
  sortArrByKey: (arr, key, isAsc = true) => {
    return arr.sort((a, b) => {
      if (isAsc) return a[key] > b[key] ? 1 : -1;
      return a[key] < b[key] ? 1 : -1;
    });
  }
};

// 文件处理助手
const fileHelper = {
  openDocument: (url) => {
    wx.showLoading({ title: '文件加载中' });
    wx.downloadFile({
      url: url,
      success: function (res) {
        wx.hideLoading();
        wx.openDocument({
          filePath: res.tempFilePath,
          success: function () {
            console.log('打开文档成功');
          },
          fail: function (err) {
            console.error('打开文档失败', err);
            wx.showToast({
              title: '打开文档失败',
              icon: 'none'
            });
          }
        });
      },
      fail: function (err) {
        wx.hideLoading();
        console.error('下载文件失败', err);
        wx.showToast({
          title: '文件下载失败',
          icon: 'none'
        });
      }
    });
  }
};

// 导出模块
module.exports = {
  // 从simple配置导入的模块
  errorHelper,
  cacheHelper,
  validate,
  timeHelper,
  statusHelper,
  logHelper,
  networkHelper,
  stateFieldHelper,
  
  // 本地定义的模块
  pageHelper,
  cloudHelper,
  dateHelper,
  dataHelper,
  fileHelper
};